/**
 * @param {number[]} stations
 * @param {number} r
 * @param {number} k
 * @return {number}
 */
 var maxPower = function(stations, r, k) {
    const s = stations.slice(Math.min(r,stations.length - r),Math.max(r,stations.length - r));
    let cnt = 0;
    let r1 = 0;
    for(let i = 0; i < r; i++){
        r1 += stations[i];
    }
    let r2 = 0;
    for(let i = stations.length - 1; i >= stations.length - r; i--){
       r2 += stations[i];
    }
    s.sort((a,b)=>a-b);
    console.log('s: ', s);
    for(let i = 0; i < s.length - 1; i++){
       cnt += (s[i+1] - s[i]) * (i + 1);
       if(cnt == k){
           let a = r1 + s[i + 1];
           let b = r2 + Math.max(s[i + 1],stations[stations.length - 1 - r]);
           return Math.min(a,b);
       }else if(cnt > k){
            let a = r1 + s[i + 1] - Math.floor((cnt - k) / (i));
            let b = r2 + Math.max(s[i + 1] - Math.floor((cnt - k) / (i)),stations[stations.length - 1 - r]);
            return Math.min(a,b);
        }
    }
    if(s.length == 0){
        let num = 0;
        for(let i = 0; i < stations.length; i++) num += stations[i];
        return num + k;
    }
    console.log('r1,r2',r1,r2);
    // console.log('ant',cnt);
    cnt = k - cnt;
    // console.log('ant',cnt);
    let a = r1 + s[s.length - 1] + Math.floor(cnt / s.length);
    let b = r2 + Math.max(s[s.length - 1] + Math.floor(cnt / s.length),stations[stations.length - 1 - r]);
    return Math.min(a,b);
};

let stations = [4,4,4,4], r = 0, k = 3;
stations = [2,10,12,3],r = 0,k = 14;//9
stations = [4,2],r = 1,k = 1;//7
// stations = [13,12,8,14,7],r = 2,k = 23;//52
// stations = [1,2,4,5,0],r = 1,k = 2;
stations = [34,15,8,26,18,23],r = 0, k = 25;
stations = [48,16,29,41,2,43,23],r = 5,k = 40;
console.log(maxPower(stations, r, k));